/**
 * <br>项目名: fastdfs-api
 * <br>文件名: UploadCtrl.java
 * <br>Copyright 2015 恒昌互联网运营中心
 */
package com.credithc.fastdfs.api.web;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.credithc.fastdfs.api.bean.RemoveReqBean;
import com.credithc.fastdfs.api.bean.RemoveResBean;
import com.credithc.fastdfs.api.bean.ResultBean;
import com.credithc.fastdfs.api.entity.FdfsInfo;
import com.credithc.fastdfs.api.service.FdfsInfoService;
import com.credithc.framework.core.utils.FastJsonConvert;

/**
 * @ClassName: RemoveCtrl
 * @Description: 文件删除
 * @author zhaoc
 * @date 2015年5月26日
 * @time 上午11:04:07
 */
@Controller
@RequestMapping("/removeFile.hc")
public class RemoveCtrl extends BaseController {
	private Logger log = LoggerFactory.getLogger(RemoveCtrl.class);
	public static final String SUCCESS = "1";// 上传成功
	public static final String FAILED = "0";// 上传失败

	@Resource(name = "fdfsInfoServiceImpl")
	private FdfsInfoService fdfsInfoServiceImpl;

	@RequestMapping(method = { RequestMethod.POST })
	public String remove(HttpServletResponse response,
			RemoveReqBean removeReqBean) throws IOException {
		RemoveResBean removeResBean = new RemoveResBean();
		removeResBean.setFsId("");
		ResultBean resultBean = new ResultBean();
		resultBean.setResult("1");
		resultBean.setErrorMsg("");
		try {
			if (handler(removeReqBean, removeResBean)) { // 文件删除操作成功
				removeResBean.setFsId(removeReqBean.getFsId());
				removeResBean.setStatus(RemoveCtrl.SUCCESS);
				removeResBean.setMessage("删除成功");
			}
		} catch (Exception ex) {
			removeResBean.setStatus(RemoveCtrl.FAILED);
			removeResBean.setMessage(ex.getMessage());
			log.warn(ex.getMessage());
			addError(ex.getMessage(), MOD_REMOVE, "/");

		}
		resultBean.setData(removeResBean);
		return ajaxHtml(FastJsonConvert.convertObjectToJSON(resultBean),
				response);
	}

	/**
	 * @Title: handler
	 * @Description: 文件状态修改操作
	 * @param
	 * @return boolean
	 * @throws
	 */
	public boolean handler(RemoveReqBean removeReqBean,
			RemoveResBean removeResBean) throws Exception {
		if (StringUtils.isBlank(removeReqBean.getFsId())) {
			removeResBean.setStatus(RemoveCtrl.FAILED);
			removeResBean.setMessage("文件ID不合法");
			return false;
		}
		FdfsInfo f = fdfsInfoServiceImpl.selectByPrimaryKey(removeReqBean
				.getFsId());
		if (f == null) {
			removeResBean.setStatus(RemoveCtrl.FAILED);
			removeResBean.setMessage("文件ID不存在");
			return false;
		}
		int i = fdfsInfoServiceImpl.updateStatusByPrimaryKey(
				removeReqBean.getFsId(), 1);
		return i > 0 ? true : false;
	}
}
